const Controller = require('egg').Controller;
const dayjs = require('dayjs')
class PaymentController extends Controller {
  async createPayPalOrder() {
    const { ctx } = this;
    const { orderId } = ctx.request.body;

    try {
      // Validate order exists and status
      const order = await ctx.service.order.findOne(orderId);
      if (!order) {
        this.ctx.error(500, 'Order not found' )
        return;
      }

      if (order.status_value !== 'wait_pay') {
        this.ctx.error(500, 'Invalid order status' )
        return;
      }

      // Create PayPal order
      const result = await ctx.service.paypal.createOrder({
        orderId: order.order_no,
        amount: order.amount,
        description: `Order ${order.order_no}`
      });

      console.log('result',result)
      if (!result.success) {
        this.ctx.error(500, 'Failed to create PayPal order' )
        return;
      }

      // Update order with PayPal order ID
      await ctx.service.order.update(orderId, {
        paypal_order_id: result.data.id,
        payment_status: 'created',
        status: 0,
        pay_way: 'paypal'
      });

      // 返回 PayPal 订单信息
      this.ctx.success({
        paypalOrderId: result.data.id,
        status: result.data.status,
        approvalUrl: result.data.approvalUrl || result.data.links.find(link => link.rel === 'approve')?.href
      });

    } catch (error) {
      this.ctx.error(500, 'Internal server error' ,error)
      ctx.logger.error('Create PayPal Order Error:', error);
    }
  }

  async verifyPayment() {
    const { ctx } = this;
    const { paypalOrderId, orderId } = ctx.request.body;

    try {
      const result = await ctx.service.paypal.verifyPayment(paypalOrderId);

      if (!result.success) {
        this.ctx.error(500, 'Failed to verify payment',result.error )
        return;
      }

      if (result.data.status === 'APPROVED') {
        const captureResult = await ctx.service.paypal.capturePayment(paypalOrderId);

        if (!captureResult.success) {
          this.ctx.error(500, 'Failed to capture payment',captureResult.error )
          return;
        }

        // Update order status
        await ctx.service.order.update(orderId, {
          status: 1,
          payment_status: 'paid',
          pay_detail: captureResult.data,
          pay_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          paypal_capture_id: captureResult.data.purchase_units[0].payments.captures[0].id
        });
        // TODO邮件推送
        this.ctx.service.email.sendEmail({
          id: orderId
        })
        this.ctx.success({
          status: 'success',
          orderId,
          paymentId: captureResult.data.id
        });
      } else {
        this.ctx.error(500, 'Payment not approved', {
          status: result.data.status
        });
      }
    } catch (error) {
      ctx.logger.error('Verify PayPal Payment Error:', error);
      this.ctx.error(500, 'Internal server error', error.message)
    }
  }

  async refundPayment() {
    const { ctx } = this;
    const { orderId, amount, note } = ctx.request.body;
    try {
      // 获取订单信息
      const order = await ctx.service.order.findOne(orderId);
      if (!order) {
        this.ctx.error(500, 'Order not found')
        return;
      }

      if (!order.paypal_capture_id) {
        this.ctx.error(500, 'No capture ID found for this order')
        return;
      }

      // 执行退款
      const refundResult = await ctx.service.paypal.refundPayment(order.paypal_capture_id, {
        amount,
        note,
        orderId
      });

      if (!refundResult.success) {
        this.ctx.error(500, 'Failed to process refund', refundResult.error)
        return;
      }

      // 更新订单状态
      await ctx.service.order.update(orderId, {
        status: 2, // 已退款状态
        payment_status: 'refunded',
        refund_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        refund_id: refundResult.data.id,
        refund_amount: amount,
        refund_remark: note
      });

      this.ctx.success({
        status: 'success',
        refundId: refundResult.data.id,
        amount: refundResult.data.amount
      });
    } catch (error) {
      ctx.logger.error('PayPal Refund Error:', error);
      this.ctx.error(500, 'Internal server error', error.message)
    }
  }
}

module.exports = PaymentController;
